package com.qf.config;/*
 * @Author: {{author}}
 * @Date:   {{create_time}}
 * @Last Modified by:   {{last_modified_by}}
 * @Last Modified time: {{last_modified_time}}
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SeruityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserDetailsService userDetailsService;

    //用来配置用户名和密码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       /* //对密码进行加密
        String encode = passwordEncoder.encode("123456");
        System.out.println(encode);
        //基于内存保存用户名和密码
        auth.inMemoryAuthentication().withUser("steel").password(encode).roles("");*/
        //通过业务类来进行认证
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }


    //配置资源请求等拦截放行规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // http.cors().disable(); //关闭跨域请求

        http.csrf().disable();//关闭默认资源拦截
        //自定义登录页面
        http.formLogin()
                .loginPage("/login.html")  //设置登录页面
                .loginProcessingUrl("/user/login")  //设置登录路径
                .defaultSuccessUrl("/index.html")   //默认登录成功跳转路径
                //   .usernameParameter("name")
                //   .passwordParameter("password")
                .permitAll();  //放行
        http.logout().logoutUrl("/user/logout")   //配置退出路径
                .logoutSuccessUrl("/login.html")
                .invalidateHttpSession(true)
                .deleteCookies("JSESSIONID")
        ;

        http.authorizeRequests()
                .antMatchers("/","/show/name","/register")  //指定的资源不拦截
                .permitAll();
        http.exceptionHandling().accessDeniedPage("/403.html");//配置指定的页面权限不足页面

        //指定的资源需要具有指定的权限
        http.authorizeRequests()
                .antMatchers("/student/update")
                //.hasAuthority()
                .hasAnyAuthority("update");
        http.authorizeRequests()
                .antMatchers("/student/**")  //访问student资源必须要有指定的角色
                .hasAnyRole("student","admin");  //有任意角色
        //          .hasRole("admin");  //指定角色

        //认证通过之后全部放行（不拦截）
        http.authorizeRequests()
                .anyRequest()
                .authenticated();

    }
}
